package com.guaju.yueshangLife.fragment.home;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.guaju.yueshangLife.BR;
import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.activity.MainActivity;
import com.guaju.yueshangLife.adapter.NoneCommonRecyclerViewAdapter;
import com.guaju.yueshangLife.base.BaseFragment;
import com.guaju.yueshangLife.bean.Goods;
import com.guaju.yueshangLife.bean.HomeTotal;
import com.guaju.yueshangLife.databinding.FragmentCategoryBinding;
import com.guaju.yueshangLife.databinding.FragmentRecommendBinding;
import com.guaju.yueshangLife.imageloader.BannerFrescoImageLoader;
import com.guaju.yueshangLife.imageloader.FrescoImageLoader;
import com.guaju.yueshangLife.net.ApiEntity;
import com.guaju.yueshangLife.utils.ScreenUtils;
import com.guaju.yueshangLife.utils.Utils;
import com.guaju.yueshangLife.viewmodel.home.RecommandVM;
import com.youth.banner.view.BannerViewPager;
import com.zhy.autolayout.AutoLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by guaju on 2018/9/28.
 */

public class RecommendFragment extends BaseFragment<FragmentRecommendBinding> {
    FragmentRecommendBinding binding;
    private static final String TYPE = "RecommendFragment";
    ArrayList<String> sliderList = new ArrayList<>();
    ArrayList<Goods> goodsList = new ArrayList<>();
    private boolean mIsPrepared;
    private boolean mIsFirst = true;
    private RecommandVM recommandVM;
    private BannerViewPager bannerViewPager;
    private View news_loading;
    private MainActivity mainActivity;

    @Override
    public int setContent() {
        return R.layout.fragment_recommend;
    }


    public static RecommendFragment newInstance(String param) {
        RecommendFragment fragment = new RecommendFragment();

        Bundle args = new Bundle();
        args.putString(TYPE, param);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EventBus.getDefault().register(this);
        binding = (FragmentRecommendBinding) bindingView;
        // 准备就绪
        mIsPrepared = true;
        mainActivity = (MainActivity) getActivity();
        loadData();
        showContentView();
        //回到顶部处理
        toTop();

        initBanner();

    }


    private void initBanner() {
        int bannerOffset = getResources().getDimensionPixelOffset(R.dimen.dp_10);
        ViewGroup viewGroup = (ViewGroup) binding.banner.getChildAt(0);
        int childCount = viewGroup.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childAt = viewGroup.getChildAt(i);
            if (childAt instanceof BannerViewPager) {
                bannerViewPager = (BannerViewPager) childAt;
            }
        }
        if (bannerViewPager != null) {
            bannerViewPager.setClipToPadding(false);
            bannerViewPager.setOverScrollMode(View.OVER_SCROLL_NEVER);
            bannerViewPager.setPageMargin((int) getResources().getDimensionPixelOffset(R.dimen.dp_5));
            bannerViewPager.setPadding(bannerOffset, 0, bannerOffset, 0);
        }
        BannerFrescoImageLoader frescoImageLoader = new BannerFrescoImageLoader();
        binding.banner.setImageLoader(frescoImageLoader);
        int screenWidth = ScreenUtils.getScreenWidth(getActivity());
        int realWidth = screenWidth - 2 * bannerOffset;
        int realHeight = realWidth * 480 / 1080;
        ViewGroup.LayoutParams layoutParams = bannerViewPager.getLayoutParams();
        layoutParams.height = realHeight;
        ViewGroup.LayoutParams bannerLayoutParams = binding.banner.getLayoutParams();
        bannerLayoutParams.height = realHeight;
        binding.banner.setLayoutParams(bannerLayoutParams);
        bannerViewPager.setLayoutParams(layoutParams);
    }

    private void toTop() {
        bindingView.scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (Math.abs(scrollY) > ScreenUtils.getScreenHeight(getActivity())) {
                    //说明滑动超过了屏幕
                    bindingView.totop.setVisibility(View.VISIBLE);
                } else {
                    bindingView.totop.setVisibility(View.INVISIBLE);
                }

            }
        });
        bindingView.totop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bindingView.scrollView.fling(0);
                bindingView.scrollView.smoothScrollTo(0, 0);
            }
        });
    }

    @Override
    protected void loadData() {
        if (!mIsPrepared || !mIsVisible || !mIsFirst) {
            return;
        }
        mIsFirst = false;
    }

    private void updateViewPager(List<HomeTotal.DataBean.CarouselBean> list) {
        for (HomeTotal.DataBean.CarouselBean bean : list) {
            sliderList.add(bean.getCover().getHost() + "/" + bean.getCover().getPath());
        }
        recommandVM.setSliderList(sliderList);
    }

    private void updateProducts() {

        NoneCommonRecyclerViewAdapter<Goods> goodsCommonRecyclerViewAdapter =
                new NoneCommonRecyclerViewAdapter<Goods>(getParentFragment().getActivity(), getLayoutInflater(), R.layout.item_goods, BR.goods, goodsList);
        bindingView.xrecyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 2) {
                                                       @Override
                                                       public boolean canScrollVertically() {
                                                           return false;
                                                       }
                                                   }
        );
        bindingView.xrecyclerview.setAdapter(goodsCommonRecyclerViewAdapter);
        bindingView.setViewmodel(recommandVM);
    }

    @Override
    protected void onVisible() {
        super.onVisible();
    }

    @Override
    protected void onInvisible() {
        // 不可见时轮播图停止滚动

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHomeReceived(HomeTotal.DataBean data) {
        recommandVM = new RecommandVM();
        if (data != null) {
            //轮播图
            List<HomeTotal.DataBean.CarouselBean> carousel = data.getCarousel();
            //人气商品
            List<HomeTotal.DataBean.ProductsBean> products = data.getProducts();
            for (HomeTotal.DataBean.ProductsBean productsBean : products) {
                String cover = productsBean.getCover().getHost() + "/" + productsBean.getCover().getPath();
                goodsList.add(new Goods(cover,
                        productsBean.getName(),
                        productsBean.getTags(),
                        productsBean.getPrice().getCurrent() + "",
                        productsBean.getId() + ""));
            }
            //更新视图和产品列表
            updateViewPager(carousel);
            updateProducts();
            //优惠券
            List<HomeTotal.DataBean.CouponsBean> coupons = data.getCoupons();
            if (coupons != null && !coupons.isEmpty()) {
                HomeTotal.DataBean.CouponsBean couponsBean = coupons.get(0);
                String couponUrl = couponsBean.getCover().getHost() + couponsBean.getCover().getPath();
                if (!TextUtils.isEmpty(couponsBean.getCover().getPath())) {
                    binding.flCoupons.setVisibility(View.VISIBLE);
                    binding.ivCoupons.setImageURI(couponUrl);
                } else {
                    binding.flCoupons.setVisibility(View.GONE);
                }
            } else {
                binding.flCoupons.setVisibility(View.GONE);
            }

            //更新 横向滑动条
//            ApiEntity.couponGoods();


            List<HomeTotal.DataBean.NoticeBean> notice = data.getNotice();
            if (notice == null || notice.isEmpty()) {
                bindingView.llSaleLayout.setVisibility(View.GONE);
            } else {
                bindingView.llSaleLayout.setVisibility(View.VISIBLE);
                for (HomeTotal.DataBean.NoticeBean noticeBean : notice) {
                    AutoLinearLayout imageContainer = (AutoLinearLayout) binding.ivNoticeContainer.inflate(getActivity(), R.layout.image_fragment_recommend, null);
                    SimpleDraweeView image = (SimpleDraweeView) imageContainer.getChildAt(0);
                    image.setImageURI(noticeBean.getCover().getHost() + noticeBean.getCover().getPath());
                    binding.ivNoticeContainer.addView(imageContainer);
                }
            }


            // 获取分类的id  便于后续 拉取产品列表


        }
        mainActivity.hideProgressPic();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
